<template>
  <div class="apply" :style="{ minHeight: bodyHeight + 'px' }">
    <overlay />
    <div class="apply-wrap" v-if="!showMaskLayer">
      <helper v-if="!applyData.length">
        <template #image>
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-kong"></use>
          </svg>
        </template>
        <span slot="helperText"> {{ $t("emptyApply") }}</span>
      </helper>
      <div
        class="applyOrder"
        v-for="(item, index) in applyData"
        :key="index"
        v-else
      >
        <div class="applyorderTop">
          <div class="userInfo">
            <div class="avatar">
              <img :src="item.avatar" />
            </div>
            <div class="supplementInfo">
              <span class="nickname">{{item.nickname}}</span>
              <span class="place">{{ getAddress(item.orderAddress) }}</span>
            </div>
          </div>
          <div class="orderPrice">&yen; {{ item.orderPrice }}</div>
        </div>
        <order-content :item="orderData[index]"></order-content>
        <myProgress :orderStatus="item.orderStatus" color="#07C160">
          <span class="progressName" slot="progressText">
            {{ $t("orders.myProgress") }}
          </span>
        </myProgress>
        <button-widget
          v-if="item.orderStatus <= 2"
          useDoWhat="cancel"
          :buttonText="$t('orders.cancel')"
          @click.native="cancelOrder(item._id, index)"
        ></button-widget>
      </div>
      <div class="block" />
    </div>
  </div>
</template>

<script>
import helper from 'components/content/helper/helper.vue';
import orderContent from 'components/content/order/content.vue';
import myProgress from 'components/content/order/progress.vue';
import buttonWidget from 'components/common/button-widget/button-widget.vue';
import overlay from 'components/content/overlay/overlay.vue';
import { mapMutations, mapState } from 'vuex';

export default {
    name: 'apply',
    components: {
        helper,
        orderContent,
        myProgress,
        buttonWidget,
        overlay
    },
    data () {
        return {
            bodyHeight: 0,
            userData: [], // 用户数据
            orderData: [], // 订单数据
            applyData: [] // 申请数据
        };
    },
    created () {
        this.resetStatus({ state: 'showMaskLayer', status: true });
        this.$api.applyApi.get(this.$store.state.userInfo._id).then(result => {
            this.forEachData(result.data);
            this.resetStatus({ state: 'showMaskLayer', status: false });
        });
    },
    mounted () {
        this.bodyHeight = this.$util.ScreenCanUseHeight(
            this.$store.state.tabbarHeight + 59
        );
    },
    methods: {
        forEachData (data) {
            this.$api.otherApi
                .axiosAll(...this.fetchOrderData(data))
                .then(orderCollections => {
                    if (orderCollections && orderCollections.length) {
                        this.$api.otherApi
                            .axiosAll(...this.fetchUserData(orderCollections))
                            .then(userCollections => {
                                this.unionData(userCollections, orderCollections);
                            })
                            .catch(err => {
                                throw err;
                            });
                    }
                })
                .catch(err => {
                    throw err;
                });
        },
        fetchOrderData (detailInfo) {
            const requestArray = [];
            _.forEach(detailInfo, value => {
                requestArray.push({
                    url: '/api/v1/orders/detail/' + value.applyOrder
                });
            });
            return requestArray;
        },
        fetchUserData (userInfo) {
            const requestArray = [];
            _.forEach(userInfo, value => {
                requestArray.push({
                    url: '/api/v1/profile/',
                    params: {
                        id: value.data.orderByCreateID
                    }
                });
            });
            return requestArray;
        },
        unionData (userCollections, orderCollections) {
            const length = userCollections.length === orderCollections.length ? userCollections.length : 0;
            if (!length) {
                this.$util.failToast('信息获取失败');
                return;
            }
            for (let index = 0; index < length; index++) {
                this.userData.push(userCollections[index].data);
                this.orderData.push(orderCollections[index].data);
                this.applyData.push(
                    Object.assign(this.userData[index], this.orderData[index])
                );
            }
            this.$nextTick(() => {
                this.$toast.clear();
            });
        },
        cancelOrder (orderId, index) {
            const params = {
                _id: orderId,
                isOrderTaked: false,
                orderStatus: 1
            };
            this.$dialog
                .confirm({ message: this.$t('orders.cancelOrder') })
                .then(() => {
                    this.$api.orderApi
                        .update(params)
                        .then(data => {
                            if (data.code === 2002) {
                                this.$api.applyApi
                                    .deleteApplyRecord({ orderId })
                                    .then(result => {
                                        if (result.code === 2028) {
                                            this.applyData.splice(index, 1);
                                            this.orderData.splice(index, 1);
                                            this.userData.splice(index, 1);
                                        } else {
                                            this.$util.failToast(result.message);
                                        }
                                    })
                                    .catch();
                            } else {
                                this.$util.failToast();
                            }
                        })
                        .catch();
                })
                .catch(() => {
                    console.warn('用户点击了取消');
                });
        },
        ...mapMutations(['resetStatus'])
    },
    computed: {
        getAddress () {
            return function (address) {
                const reg = /市/;
                return '发布于' + address.substring(0, address.search(reg) + 1);
            };
        },
        ...mapState(['showMaskLayer'])
    }
};
</script>

<style scoped lang="less" src="./less/my-apply.less"></style>
